#include "comm.hpp"
#include "Log.hpp"

//充当创建共享内存的角色
int main()
{


    key_t key = CreatKey();
    Log() << "key " << key <<endl;


    Log() << "create share memory begin! \n";
    //sleep(5);
    //创建一个全新的共享内存
    int shmid = shmget(key,MEM_SIZE,IPC_CREAT|IPC_EXCL | 0666);
    if(shmid < 0)
    {
        Log()<<"shmget:" << strerror(errno) << endl;
        return 2;
    }

    Log() << "creat shm success ,shmid: " << shmid << endl;


    //创建管道
    CreateFifo();
    int fd = Open(FIFO_FILE,READER);
    assert( fd >= 0);

    
    sleep(2);
    //使用
    //1.将共享内存挂接到进程地址空间内
    char * str = (char*)shmat(shmid,nullptr,0);
    Log()<< " attach shm : " << shmid << "sucess !\n";
    //sleep(2);

    //2.使用
    while(true)
    {
        //让读端进行等待
        //有数据了再读
        if(Wait(fd) == 0) break;

        printf("%s\n",str);
        sleep(1);
    }
    
    //2.不想用就去关联
    shmdt(str);
    Log()<< " detach shm : " << shmid << "sucess !\n";

    
    sleep(2);


    //删除
    shmctl(shmid,IPC_RMID,nullptr);
    Log()<<"delete shm : " << shmid << "sucess \n";


    Close(fd,FIFO_FILE);
    //sleep(5);
    return 0;
}